//
//  LogTool.swift
//  downloadImage
//
//  Created by Galaxy on 2022/6/20.
//

import UIKit
import SwiftDate

class LogTool: NSObject {
    // 创建log文件
    func makeLogFile(){
        let todayDate = DateInRegion().dateAt(.startOfDay)
        let fileName = todayDate.toFormat("yyyy-MM-dd")+".log"
        let filePath = "\(FileTool.init().getDocumentPath())/logFile"
        do {
            let result = try FileTool.init().createDirectory(path: filePath)
            if result {
                if FileTool.init().createLocalFile(savePath: filePath, fileName: fileName, fileData: Data.init()) {
                    print("log生成成功,\(filePath)")
                }
            }
        } catch let error {
            print(error.localizedDescription)
        }
    }
    
    // 读取log文件
    func readLogFile()->String{
        let todayDate = DateInRegion().dateAt(.startOfDay)
        let fileName = todayDate.toFormat("yyyy-MM-dd")+".log"
        let filePath = "\(FileTool.init().getDocumentPath())/logFile"
        print(filePath+"/"+fileName)
        do {
            let fileData = try Data.init(contentsOf: URL.init(fileURLWithPath: filePath+"/"+fileName))
            let fileContent = String.init(data: fileData, encoding: .utf8)
            return fileContent!
        } catch let error {
            print(error.localizedDescription)
            return ""
        }
    }
    
    // 保存log
    func saveLog(logContent:String) -> Bool{
        let todayDate = DateInRegion().dateAt(.startOfDay)
        let fileName = todayDate.toFormat("yyyy-MM-dd")+".log"
        let filePath = "\(FileTool.init().getDocumentPath())/logFile"
        let fileData = logContent.data(using: .utf8)
        return FileTool.init().updateLocalFile(savePath: filePath, fileName: fileName, fileData: fileData!)
    }
    
    // 删除log
    func deleteLog() {
        let todayDate = DateInRegion().dateAt(.startOfDay)
        let filePath = "\(FileTool.init().getDocumentPath())/logFile"
        _ = FileTool.init().deleteFileWithPath(path: filePath)
    }
}
